// 打印工具
import html2canvas from "html2canvas";
import printJs from "print-js";

export class PrintUtils {
  static printById(id: string) {
    const elementById = document.getElementById(id);
    if (elementById) {
      return PrintUtils.printByDom(elementById)
    }
    return Promise.resolve()
  }

  static printByDom(dom: HTMLElement) {
    // 此处是实现滚动元素长截图的关键 start
    // 记录当前元素的宽高和滚动位置
    const info = {
      width: dom.style.width,
      height: dom.style.height,
      scrollTop: dom.scrollTop,
      scrollLeft: dom.scrollLeft
    }
    // 完全撑开
    dom.style.width = dom.scrollWidth + 'px'
    dom.style.height = dom.scrollHeight + 'px'
    // 此处是实现滚动元素长截图的关键 end
    return new Promise<void>(resolve => {
      html2canvas(dom, {useCORS: true, height: dom.scrollHeight, width: dom.scrollWidth})
        .then(canvas => {
          const imgData = canvas.toDataURL('image/png')
          printJs(imgData, 'image')
        })
        .finally(() => {
          // 恢复元素信息
          dom.style.width = info.width
          dom.style.height = info.height
          dom.scrollTop = info.scrollTop
          dom.scrollLeft = info.scrollLeft
          resolve()
        })
    })
  }
}
